package io.zerous.zexgraph;

import android.content.Context;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Zerous on 2018/7/22.
 */
public class FileUtils {
    public static void saveTextFile(Context c, String name, String text) {
        FileOutputStream fileOutputStream;
        try {
            fileOutputStream = c.openFileOutput(name, Context.MODE_PRIVATE);
            fileOutputStream.write(text.getBytes());
            fileOutputStream.close();
        } catch (Exception e) {

        }
    }

    public static String[] getSrcFileNames(Context context) {
        File[] fList = context.getFilesDir().listFiles();
        List<String> list = new ArrayList<>();

        for (int i = 0;i < fList.length;++i) {
            if (fList[i].getName().contains("lua")) {
                list.add(fList[i].getName());
            }
        }

        String[] result = new String[list.size()];
        for (int i = 0;i < result.length;++i) {
            result[i] = list.get(i);
        }

        return result;
    }

    public static void deleteFile(Context c, String fileName) {
        File f = new File(c.getFilesDir(), fileName);

        if (f.exists() && f.isFile()) {
            if (f.delete()) {
                Toast.makeText(c, "删除成功~", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(c, "什么？竟然失败了！", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(c, "这个文件已经不存在了。", Toast.LENGTH_SHORT).show();
        }
    }

    public static String readTextFile(Context c, String fileName) {
        File f = new File(c.getFilesDir(), fileName);

        String result = "";

        BufferedReader bufferedReader;

        try {
            bufferedReader = new BufferedReader(new FileReader(f));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }

            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
